'''
1.基于协议
接口代码 requests
通过分析页面找到验证点，断言 re/bs4
2.多线程
模拟真实用户使用 threading.Thread
3.模拟用户场景
思考时间 time,random
拱形、门型、复杂场景   循环
4.指标收集
响应时间  时间戳  装饰器
吞吐量    psutil
资源利用率
每秒事务数
事务成功率

5.性能测试报告
'''
from threading import Thread

import psutil
import requests,time,pymysql
s = requests.session()
ph=15756492607

def get_data(string):
    string = string.replace("&", '","')
    string = string.replace("=", '":"')
    string = '{"' + string + '"}'
    return eval(string)

def get_time(func):
    def inner():
        start_time=time.time()
        resp=func()
        end_time=time.time()
        return round(end_time-start_time,2),resp
    return inner

@get_time
def get_login():
    string = 'username=admin&password=admin123&verifycode=0000'
    url="http://localhost:8080/woniusales/user/login"
    data=get_data(string)
    req=s.post(url,data)
    if req.text=='login-pass':
        return 'pass'
    else:
        return 'fail'

@get_time
def add_customer():
    global ph
    string=f'customername=未知&customerphone={ph}&childsex=男&childdate=2021-03-23&creditkids=0&creditcloth=0'
    url='http://localhost:8080/woniusales/customer/add'
    data = get_data(string)
    req = s.post(url, data)
    ph+=1
    print(req.text)
    if req.text in 'add-successful':
        return 'pass'
    else:
        return 'fail'

@get_time
def search_customer():
    string = "customerphone=15881111111&page=1"
    param = get_data(string)
    resp = s.post("http://localhost:8080/woniusales/customer/search", data=param,).text
    if "15881111111" in resp:
        return "pass"
    else:
        return "fail"

def loop(num):  # 执行次数
    for i in range(num):
        r = get_login()
        print(r)
        r = add_customer()
        print(r)
        r = search_customer()
        print(r)

def add_vusers(users=0,loopnum=0):  # 用户数
    user_list=[]
    for i in range(users):
        t=Thread(target=loop,args=(loopnum,))
        user_list.append(t)
    for i in user_list:
        i.start()
    for i in user_list:
        i.join()

def get_resource():
    while True:
        print('cpu利用率:', psutil.cpu_percent(interval=1), end='   ')
        print('内存利用率:', psutil.swap_memory()[-3], end='')  # 内存利用率
        print('网络send:', psutil.net_io_counters()[0], end='')  # 网络
        print('网络recv:', psutil.net_io_counters()[1], end='')
        print('磁盘read:', psutil.disk_io_counters()[0], end='')  # 磁盘读写
        print('磁盘write:', psutil.disk_io_counters()[1])
        # time.sleep()


if __name__ == '__main__':
    # get_login()
    # print(add_customer())
    # search_customer()
    # for i in range(10):
    #     add_customer()
    # loop(10)
    t = Thread(target=get_resource,daemon=True)
    t.start()

    add_vusers(200,100)
































